//
//  TalkDetailController.m
//  QQplayground
//
//  Created by zhangxy on 2018/7/20.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "TalkDetailController.h"

#import "ZZTalkListCell.h"
#import "ZZKeyboardView.h"
#import "ZZContentCommentController.h"

#import "ZZDetailCommentCell.h"
#define cellIdentifier @"ZZDetailCommentCell"

#import "ZZShareView.h"
#import "ZZShareCardController.h"
#import "ReportView.h"
#import "LoginController.h"
@interface TalkDetailController ()<ZZTopicCellDelegate,UIGestureRecognizerDelegate>{
    int _page;
    NSString *image_id;
}

@property(nonatomic,strong)  NSMutableArray *listArray;
@property(nonatomic,strong)  UITableView *listTable;

@property(nonatomic,strong)  ZZTalkListCell *headerCellView;
@property(nonatomic,strong)  ZZKeyboardView   *keyboardView;

@end

@implementation TalkDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"帖子";
    // Do any additional setup after loading the view.
//    if(convertToString(_model.user_info.user_name).length == 0){
//        self.navigationItem.title = @"帖子";
//    }else{
//        self.navigationItem.title = convertToString(_model.user_info.user_name);
//    }
    [self setNavigationBar];
    
    
    self.navigationController.navigationBarHidden = NO;
    
    [self createTableView];
    
    
    
    _keyboardView = [[ZZKeyboardView alloc] initWithDelegate:self changeView:_listTable show:NO style:ZZKeyboardControlsAddPhoto];
    _keyboardView.chatpterModel = _model;
    __weak TalkDetailController *saveSelf = self;
    [_keyboardView setResultBlock:^(int code,NSString *text,id replayModel){
        if(code == 0){
            
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            [dict setObject:convertToString(saveSelf.model.thread_id) forKey:@"thread_id"];
            [dict setObject:convertToString([UserUtil getUser].user_id) forKey:@"session_uid"];
            [dict setObject:convertToString(saveSelf.model.cat_id) forKey:@"cat_id"];
            
            [dict setObject:convertToString(text) forKey:@"message"];
            [dict setObject:@"reply" forKey:@"action_type"];
            [dict setObject:convertToString(image_id) forKey:@"img_id"];
            
            NSString *api = API_publishPost;
            if(replayModel!=nil){
                ZZTopicCommentEntity *tempModel = replayModel;
                [dict setObject:convertToString(tempModel.comment_id) forKey:@"post_id"];
                
                api = API_publishReplyPost;
            }
            
            [NetworkUtil POST:api parameters:dict success:^(id responseObject, NSDictionary *dict) {
                ZZTopicCommentEntity *addModel = [[ZZTopicCommentEntity alloc] initWithDictionary:dict[@"data"]];
                if(replayModel!=nil){
                    ZZTopicCommentEntity *com = replayModel;
                    [com.thread_list insertObject:addModel atIndex:0];
                }else{
                    [saveSelf.listArray insertObject:addModel atIndex:0];
                }
                [saveSelf.listTable reloadData];
            } failure:^(NSError *error, NSString *message) {
//                NSLog(@"message999999999%@",message);
//                [PopUtil showMessage:message];
                [self showLogin];
            }];
        }
    }];
    
    
    
    UITapGestureRecognizer *oneTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pageClick:)];
    oneTap.delegate = self;
    oneTap.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:oneTap];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
     self.navigationController.navigationBar.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
    
}

-(void)pageClick:(UITapGestureRecognizer *) tap{
    [_keyboardView hideKeyboard];
}


- (void)imagePickerDidFinishedWithInfo:(NSDictionary *)info image:(UIImage *) thumIamge file:(NSURL *) url type:(ImagePickerDelegateType) type{
    if(thumIamge){
        NSData *data = UIImageJPEGRepresentation(thumIamge,0.3);
        
        [ImageUploadUtil uploadImage:data api:API_ForumUpload  param:@{@"session_uid":[UserUtil getUser].user_id} callback:^(NSString *imageurl, NSDictionary *videoDict, NSString *message) {
//            NSLog(@"%@",videoDict);
            
            if(videoDict){
                self->image_id = videoDict[@"image_id"];
                if(_keyboardView){
                    [_keyboardView setUploadResutl:videoDict image:thumIamge];
                }
            }else{
                [PopUtil showMessage:message];
            }
            
        }];
    }
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 输出点击的view的类名
//    NSLog(@"%@", NSStringFromClass([touch.view class]));
    
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        [_keyboardView hideKeyboard];
        return NO;
    }
    return  YES;
}


- (UIView *)headerView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0)];

    _headerCellView = [[NSBundle mainBundle]loadNibNamed:@"ZZTalkListCell" owner:nil options:nil].firstObject;
    _headerCellView.delegate = self;
    [_headerCellView dataToView:_model];
    
    
    //    UIImage *backImage =[UIImage imageNamed:@"voice_bg"];
    //    headerView.layer.contents=(id)backImage.CGImage;
    //    self.view.layer.backgroundColor = [UIColor clearColor].CGColor;
    headerView.layer.backgroundColor = UIColor.clearColor.CGColor;
    [headerView addSubview:_headerCellView];
    
    [headerView setFrame:CGRectMake(0, 0, ScreenWidth, CGRectGetMaxY(_headerCellView.frame))];
    
    return headerView;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [_keyboardView hideKeyboard];
}



-(void)createTableView{
    _listArray = [[NSMutableArray alloc] init];
    
    _listTable=[self.view createTableView:self cell:cellIdentifier formY:0 withHeight:self.view.bounds.size.height-BottomHeight];
    
    [_listTable setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    
    _listTable.tableHeaderView = [self headerView];
    
    [_listTable setSeparatorColor:LINE_COLOR];
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    
    MJRefreshBackStateFooter *footer = [MJRefreshBackStateFooter  footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    _listTable.footer = footer;
    [self setTableSeparatorInset];
    
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [self loadBegin];
}


-(void)loadBegin{
    _page = 1;
    [self loadMoreData];
}


-(void)onCellItemClick:(ZZTopicCellClickType)type obj:(id)senderObj{
    if(type == ZZClickComment){
        [_keyboardView.textField becomeFirstResponder];
        return;
    }
    if (![UserUtil getUser].isOnline){
        if (type == ZZClickStar){
            [self showLogin];
            return ;
        }
    }
    [ZZCoreTools sucaiListenerImpl:senderObj type:type page:self refresh:_listTable];
}

// 只看楼主
-(void)lookMySelf:(UIButton *) btn{
    
}

/**
 加载更多
 */
-(void)loadMoreData{
    DLog(@"-----------------load");
    NSDictionary *p = @{@"thread_id":_model.thread_id,
                        @"see_lz":@"0",
                        @"reply_page":@"1",
                        @"page":convertIntToString(_page)
                        };
    [NetworkUtil POST:API_GetForumDetail parameters:p success:^(id responseObject, NSDictionary *dictionary) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
        if(self->_page == 1){
            self->_model = [[ForumEntity alloc] initWithDictionary:dictionary[@"data"][@"thread"]];
            _keyboardView.chatpterModel = _model;
            //self.navigationItem.title = convertToString(_model.user_info.user_name);
            
            _listTable.tableHeaderView = [self headerView];
            [self.listArray removeAllObjects];
            
            if(_replyModel){
                [self->_keyboardView setReplyModel:_replyModel];
            }
        }
        NSArray *arr = dictionary[@"data"][@"list"];
        for(NSDictionary *item in arr){
            if([item isKindOfClass:[NSDictionary class]]){
                ZZTopicCommentEntity *model = [[ZZTopicCommentEntity alloc] initWithDictionary:item];
                
                [self.listArray addObject:model];
            }
            
        }
        [self.listTable reloadData];
        
        if(self->_page == 1 && self.listArray.count > 0){
            NSIndexPath * dayOne = [NSIndexPath indexPathForRow:0 inSection:0];
            [self->_listTable scrollToRowAtIndexPath:dayOne atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
        
        if(convertToString(dictionary[@"data"][@"page"]).length>0){
            if([dictionary[@"data"][@"page"] intValue] < [dictionary[@"data"][@"pages"] intValue]){
                self->_page = [dictionary[@"data"][@"page"] intValue] + 1;
            }
        }
        
    } failure:^(NSError *error, NSString *message) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
    }];
}



#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 54;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 54)];
    [headerView setBackgroundColor:UIColor.whiteColor];
    
    UIImageView *lineView = [self createImageView];
    [lineView setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    [lineView setFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    [headerView addSubview:lineView];
    
    UILabel *labTip = [self createLabel];
    [labTip setFont:FontThirteen];
    [labTip setTextColor:UIColorFromRGB(Text6Color)];
    [labTip setFrame:CGRectMake(10, 10, ScreenWidth - 64, 44)];
    [headerView addSubview:labTip];
//    if(section == 0){
//        [_headerCellView dataToView:_model];
//        _listTable.tableHeaderView = _headerCellView;
//
//        [labTip setText:@"热门评论"];
//    }else{
        [labTip setText:@"全部评论"];
        
//        UIButton *btnOnlySelf = [self createButton];
//        [btnOnlySelf setTitle:@"只看楼主" forState:0];
//        [btnOnlySelf setFrame:CGRectMake(ScreenWidth-73, (44-18)/2+10, 63, 18)];
//        [btnOnlySelf setTitleColor:UIColorFromRGB(TextWhiteColor) forState:0];
//        [btnOnlySelf.titleLabel setFont:FontThirteen];
//        btnOnlySelf.layer.cornerRadius = 3.0f;
//        btnOnlySelf.layer.masksToBounds = YES;
//        [btnOnlySelf setBackgroundColor:UIColorFromRGB(TextLinkColor)];
//        [btnOnlySelf addTarget:self action:@selector(lookMySelf:) forControlEvents:UIControlEventTouchUpInside];
//        [headerView addSubview:btnOnlySelf];
//    }
    
    return headerView;
}


// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _listArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZZDetailCommentCell *cell = (ZZDetailCommentCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ZZDetailCommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    cell.nav_type = @"forum";
    cell.delegate = self;
    [cell dataToView:_listArray[indexPath.row]];
    
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ZZTopicCommentEntity *entity=[_listArray objectAtIndex:indexPath.row];
    
    if (![UserUtil getUser].isOnline){
        [[ZZCoreTools getCoreTools] showLogin:self];
        return;
    }
    
    [[AlertUtil shareInstance] showSheet:nil message:nil cancelTitle:@"取消" viewController:self confirm:^(NSInteger buttonTag) {
        if(buttonTag == 0){
            [self->_keyboardView setReplyModel:entity];
        }
        if(buttonTag == 1){
            ZZShareCardController *vc = [[ZZShareCardController alloc] init];
            vc.forum = self->_model;
            vc.replyModel = entity;
            [self openPushVC:vc];
        }
        if(buttonTag == 2){
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string = convertToString(entity.message);
            
            [PopUtil showMessage:@"已复制到剪切板"];
        }
        if(buttonTag == 3){
            ReportView *report = [[ReportView alloc] initWithShareType:self];
            report.mapping_id = entity.comment_id;
            report.mapping_uid = entity.user_info.user_id;
            report.report_type = @"thread";
            [report show];
        }
    } buttonTitles:@"回复",@"分享",@"复制",@"举报", nil];
    
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if((indexPath.row+1) < _listArray.count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}



#pragma mark UITableView delegate end
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
//请登录
-(void)showLogin{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:Unlogin_tip message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *login = [UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        LoginController *loginVC = [[LoginController alloc] init];
        [self addChildViewController:loginVC];
        [self.navigationController pushViewController:loginVC animated:YES];
    }];
    [alert addAction:cancle];
    [alert addAction:login];
    [self presentViewController:alert animated:YES completion:nil];
}
@end
